/**
 * @author ZhiWen Ren
 * @version 1.0
 * @description: LeetCode-74-在排序数组中查找元素的第一个和最后一个位置
 * @date 2025/5/21 10:42
 */
public class Solution34 {
    public int[] searchRange(int[] nums, int target) {
        int n = nums.length;
        if (n == 0) {
            return new int[]{-1, -1};
        }
        int firstPosition = findFirstPosition(nums, target);
        if (firstPosition == -1) {
            // target不在nums数组中
            return new int[]{-1, -1};
        }
        int lastPosition = findLastPosition(nums, target);
        return new int[]{firstPosition, lastPosition};
    }

    private int findFirstPosition(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = (left + right) >>> 1;
            if (nums[mid] > target) {
                right = mid - 1;
            } else if (nums[mid] == target) {
                // mid的右边一定不可能是firstPosition
                right = mid;
            } else {
                // nums[mid] < target
                left = mid + 1;
            }
        }
        if (nums[left] == target) {
            // right == left
            return left;
        }
        return -1;
    }

    private int findLastPosition(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left < right) {
            int mid = (left + right + 1) >>> 1; // +1是为了防止left永远等于mid陷入死循环
            if (nums[mid] < target) {
                left = mid + 1;
            } else if (nums[mid] > target) {
                right = mid - 1;
            } else {
                // mid的左边一定不可能是lastPosition
                left = mid;
            }
        }
        // target一定存在于nums中，直接返回left即可，不存在left > right 的情况
        return left;
    }
}
